
#include "fig_ui_levelcomplete.h"
#include "fig_trophie_notification.h"
#include "fighter.h"
#include "gen_game_state.h"
#include "fig_sounds.h"
#include "fig_award_tracker.h"
#include "lang/lang.h"
#include "fig_vars.h"
#include "fig_ios_wrapper.h"
#include "fig_constants.h"
#include "fig_gamecenter.h"
#include "fig_ios_wrapper.h"
//#include "fig_ui_removead.h"

#include "ui/ui_checkbox.h"
#include "ui/ui_manager.h"
#include "gameflow/game_flow_manager.h"
#include "gameflow/ui_popup.h"
#include "gameflow/ui_state.h"
#include "font/font_manager.h"
#include "graphics/graphics.h"
#include "graphics/graphics_util.h"
#include "application/game_application.h"
#include "util/log.h"
#include "util/profiler.h"

#ifdef _PLATFORM_ANDROID
#include "SDL2/src/core/android/SDL_android.h"
#include "android/sleipner_android.h"
#endif


using namespace gameflow;



FIGUILevelComplete::FIGUILevelComplete(const std::string& File):
			FIGUIPopupAnimator( File ,"button_next" ),
			m_PopupReshowCounter(0.0f),
			m_ToCloseMedalInfoPopup(false),
			m_IsAlreadyOnClickScreen(false),
			m_BaseScore(0),
			m_TotalScore(0),
			m_CarryScore(0)
{
   
	m_AlphaCounter.SetLimit(1.0f);

	FIGUIPopupAnimatorMgr::Instance().AddPopupAnimator(FIGUIPopupAnimatorMgr::POPUP_NAMES_GAMEOVER,this);
	m_Type = ANIMATION_SLIDEFROMTOP;

	if(m_pPopup)
	{
		AddToNaviationUI(m_pPopup->GetWidget("button_next"));
        
        if(m_pPopup->GetWidget("button_next"))
            m_ButtonNextPosBackup = m_pPopup->GetWidget("button_next")->GetPosition();

		m_pUIInfoTxt = m_pPopup->GetWidget("info");
		m_pUIInfoTxtBg = m_pPopup->GetWidget("txtbg");

	
	//SetWidgetFunctor("BG",UI_DELEGATE(FIGUILevelComplete, OnClickScreen));
		m_pPopup->SetWidgetFunctor("button_next",UI_DELEGATE(FIGUILevelComplete, OnClickScreen));

	//#ifdef _PLATFORM_ANDROID
		//m_pPopup->SetWidgetFunctor("button_removead",UI_DELEGATE(FIGUILevelComplete, OnButtonAndroidRateUs));
	//#else
	//	SetWidgetFunctor("button_removead",UI_DELEGATE(FIGUILevelComplete, OnButtonFullVersion));
	//#endif

		m_pUIScore1 = m_pPopup->GetWidget("score1");
		m_pUIScore2 = m_pPopup->GetWidget("score2");
		m_pUIScore3 = m_pPopup->GetWidget("score3");
		m_pUIScore4 = m_pPopup->GetWidget("score4");

		m_pUIBonus1 = m_pPopup->GetWidget("bonus1");
		m_pUIBonus2 = m_pPopup->GetWidget("bonus2");
		
	}
	

	InitWidgetNumber(m_pUIScore1);
	InitWidgetNumber(m_pUIScore2);   
	InitWidgetNumber(m_pUIScore3);
	InitWidgetNumber(m_pUIScore4);	 	

	InitWidgetNumber(m_pUIBonus1);	 
	InitWidgetNumber(m_pUIBonus2);

	m_BonusCounter.SetLimit(1.0f);
	m_ScoreCounter.SetLimit(1.0f);


	char	Buffer[256];
	for(int i = 0; i < FIGGameCenter::ACHIEVEMENT_C; i++)
	{    		
		sprintf(Buffer, "medal_%i", i+1);
		m_pUIMedals[i] = m_pPopup->GetWidget(Buffer);

		m_pPopup->SetWidgetFunctor(Buffer, UI_DELEGATE(FIGUILevelComplete, OnClickMedal));

		sprintf(Buffer, "IsNewM_%i", i+1);
		m_pUIIsNew[i] = m_pPopup->GetWidget(Buffer);
	}

	ui::UIWidget* pWidget = m_pPopup->GetWidget("perc_1");
	if(pWidget)
		pWidget->SetTextW(L"%");
	pWidget = m_pPopup->GetWidget("perc_2");
	if(pWidget)
		pWidget->SetTextW(L"%");
	 
}

void	FIGUILevelComplete::InitWidgetNumber(ui::UIWidget* pWidget)
{
	if(pWidget)
	{
		//pWidget->SetTextColor(0.0f,1.0f,0.0f,1.0f);
		pWidget->SetTextA("0");
	}
}

void	FIGUILevelComplete::Show()
{

	if(FIGUIPopupAnimatorMgr::Instance().GetPopup(FIGUIPopupAnimatorMgr::POPUP_NAMES_MEDALINFO)->GetPopup()->IsActive())
		return;	// dun show it yet
	
	m_IsAlreadyOnClickScreen = false;
	
	// Enemies Kill
	int EnemiesKilledPerc = FIGAwardTracker::Instance().GetEnemiesKilledPerc();
	if(m_pUIScore1)
		m_pUIScore1->SetTextA( lang::Lang::FormatNumber(EnemiesKilledPerc));

	// Stars
	int StarObtainedPerc = FIGAwardTracker::Instance().GetStarObtainedPerc();
	if(m_pUIScore2)
		m_pUIScore2->SetTextA( lang::Lang::FormatNumber(StarObtainedPerc));


	int EnemiesKilled = FIGAwardTracker::Instance().GetEnemyKilled();
	m_TotalScore = FIGVars::Instance()->GetInt(FIGVars::VAR_NAMES_HIGHSCORE);
	m_BaseScore = FIGAwardTracker::Instance().GetCurrentLevelScore();

	// Difiiculty
	// deprecated
	int Difficulty = 0; //FIGVars::Instance()->GetInt(FIGVars::VAR_NAMES_DIFFICULTY);
	Difficulty *= 10;
	if(m_pUIScore3)
		m_pUIScore3->SetTextA( lang::Lang::FormatNumber(Difficulty,true));
	
	// Total Score
	if(m_pUIScore4)
		m_pUIScore4->SetTextA( lang::Lang::FormatNumber(m_TotalScore + m_BaseScore,true));


	// Bonuses
	m_BonusScore1 = (int)(m_BaseScore * ((float)EnemiesKilledPerc/100.0f));
	m_BonusScore2 =	(int)(m_BaseScore * ((float)StarObtainedPerc/100.0f));
	
	// deprecated 
	m_BonusScore2  = 0;

	if(m_pUIBonus1)
		m_pUIBonus1->SetTextA( lang::Lang::FormatNumber(m_BonusScore1,true));

	if(m_pUIBonus2)
		m_pUIBonus2->SetTextA( lang::Lang::FormatNumber(m_BonusScore2,true));

	
	LoadMedals();


	m_BonusCounter.Reset();
	m_ScoreCounter.Reset();
	//GENGameState::GetGame()->TickMe(m_pPopup);

	
	if(FIGTrophieNotification::Instance().GetLastTrophieID() > 0)
	{
		char	Buffer[256];	
		sprintf(Buffer, "medal_%i", FIGTrophieNotification::Instance().GetLastTrophieID());

		ui::UIWidget* pWidget =  m_pPopup->GetWidget(Buffer);
		if(pWidget)
		{
			OnClickMedal(ui::UIWidget::WE_LMB_CLICK,pWidget);
		}

		FIGTrophieNotification::Instance().ClearLastTrophieID();	
	}
	else
	{
		FIGUIPopupAnimator::Show();
	}
	
}


void					FIGUILevelComplete::LoadMedals()
{
	// Medals
	int j = 0;
	for(int i = FIGVars::VAR_NAMES_ACHIEVEMENT_1; i < FIGVars::VAR_NAMES_ACHIEVEMENT_10; i++)
	{
		if(m_pUIMedals[j])
		{
			if(FIGVars::Instance()->GetInt(i))
			{
				m_pUIMedals[j]->SetIsVisible(true);					
			}
			else
			{
				m_pUIMedals[j]->SetIsVisible(false);

			}
		}

		if(FIGAwardTracker::Instance().IsGotAwardThisLevel(j+1))
		{
			if(m_pUIIsNew[j])
				m_pUIIsNew[j]->SetIsVisible(true);
		}
		else
		{
			if(m_pUIIsNew[j])
				m_pUIIsNew[j]->SetIsVisible(false);
		}
		j++;
	}
}



void DELEGATE_CALL		FIGUILevelComplete::OnClickScreen(ui::UIWidget::WIDGET_EVENT Event, ui::UIWidget* pWidget)
{
	
	if(m_IsAlreadyOnClickScreen)
		return;

	m_IsAlreadyOnClickScreen = true;
	
	if(m_pPopup)
		m_pPopup->Hide(NULL);

	GoToNextLevel();

    /*
	if( ((FIGVars*) FIGVars::Instance())->GetCurrentLevel() == 3 ||
		((FIGVars*) FIGVars::Instance())->GetCurrentLevel() == 7
		)
	{
		if(FIGVars::Instance()->GetInt(FIGVars::VAR_NAMES_RATE_CLICKED) == 0)
		{

			std::string RateText = "Enjoying? Please rate us.";
			if( ((FIGVars*) FIGVars::Instance())->GetCurrentLevel() == 7)
			{
				RateText = "You have completed all levels, Please encourage us to make more levels by rating the game.";
			}


		// ask whether he wants to rate the game or not
			gameflow::UIPopupManager::Instance().StartYesNo(RateText, 
											UI_DELEGATE(FIGUILevelComplete, OnButtonRateUs),
											UI_DELEGATE(FIGUILevelComplete, OnButtonCancel)
											);
		}
		else
		{
			GoToNextLevel();
		}
	}
	else
	{
     */

		//AdManager::Instance().RequestFullScreenAd(2);
		
    
	//}
	
}

void DELEGATE_CALL		FIGUILevelComplete::OnButtonRateUs(ui::UIWidget::WIDGET_EVENT Event, ui::UIWidget* pWidget)
{
	// redirect to the game rating page.

    //FIGIOSWrapper::Instance().FIG_GotoWebSite("itms://itunes.com/apps/aliencrusher");  
	FIGIOSWrapper::Instance().FIG_GotoWebSite(FIGConstants::ITUNE_LINK);

	FIGVars::Instance()->SetInt(FIGVars::VAR_NAMES_RATE_CLICKED,1);
    
	GoToNextLevel();
}
	
void DELEGATE_CALL		FIGUILevelComplete::OnButtonCancel(ui::UIWidget::WIDGET_EVENT Event, ui::UIWidget* pWidget)
{
	GoToNextLevel();
}

void	FIGUILevelComplete::GoToNextLevel()
{
	Fighter::Instance().GoToNextLevel();
	gameflow::UIPopupManager::Instance().HideAllPopups();

	FIGVars::Instance()->SetInt(FIGVars::VAR_NAMES_HIGHSCORE, m_CarryScore);
}

void	FIGUILevelComplete::Tick(float dt)
{
	if(!m_pPopup)
		return;

	if(!m_pPopup->IsActive())
		return;

	RefreshUI();

	if(m_PopupReshowCounter > 0)
	{
		m_PopupReshowCounter -= dt;
		if( m_PopupReshowCounter <= 0)
			m_pPopup->GetWidget("BG")->SetIsVisible(true);
			
	}

	//if(m_ToCloseMedalInfoPopup)
	//{
	//	deprecated
	//	m_ToCloseMedalInfoPopup = false;
	//	gameflow::UIPopupManager::Instance().EndPopup("ui/popup_medal_info.ui");
		
	//}    	
	//else 
	if(m_PopupReshowCounter <= 0)
	{
		if(!m_pPopup->GetWidget("BG")->GetIsVisible())
		{
			//gameflow::UIPopup* pPopup = gameflow::UIPopupManager::Instance().StartPopup("ui/popup_medal_info.ui");
			FIGUIPopupAnimator* pPopupAni = FIGUIPopupAnimatorMgr::Instance().Show(FIGUIPopupAnimatorMgr::POPUP_NAMES_MEDALINFO);
			if(pPopupAni && pPopupAni->GetPopup())	
			{
				pPopupAni->GetPopup()->SetWidgetFunctor("button_ok",UI_DELEGATE(FIGUILevelComplete, OnClosePopupMedal));
				FIGUIPopupAnimatorMgr::Instance().GetPopup(FIGUIPopupAnimatorMgr::POPUP_NAMES_GAMEOVER)->GetPopup()->Hide(NULL);
			}
			return;
		}
	}

	m_AlphaCounter.Tick(dt);
	if(m_AlphaCounter.IsReady())
		m_AlphaCounter.Reset();
	float Counter = m_AlphaCounter.GetCounter();
	float Alpha = 0;
	if(Counter < 0.5f)
		Alpha = Counter;
	else
		Alpha = 1.0f - Counter;
	

	Alpha += 0.7f;
	if(Alpha > 1.0f)
		Alpha = 1.0f;

	if(m_pUIInfoTxt)
		m_pUIInfoTxt->SetTextColor(Alpha,Alpha,Alpha,1.0f); 
	//------------------------------------------------

	m_BonusCounter.Tick(dt);
	int SubBonus1 = (int)((float)m_BonusScore1 * m_BonusCounter.GetProgress());
	int SubBonus2 = (int)((float)m_BonusScore2 * m_BonusCounter.GetProgress());
	

	if(m_pUIBonus1)
		m_pUIBonus1->SetTextA( lang::Lang::FormatNumber(SubBonus1 ,true));

	if(m_pUIBonus2)
		m_pUIBonus2->SetTextA( lang::Lang::FormatNumber(SubBonus2 ,true));


	if(m_BonusCounter.IsReady())
	{

		if(m_ScoreCounter.IsReady())
			return;

		m_ScoreCounter.Tick(dt);

		SubBonus1 = (int)((float)m_BonusScore1 * m_ScoreCounter.GetProgress());
		SubBonus2 = (int)((float)m_BonusScore2 * m_ScoreCounter.GetProgress());
	

		m_CarryScore = m_TotalScore + m_BaseScore + SubBonus1 + SubBonus2;
		if(m_pUIScore4)
			m_pUIScore4->SetTextA( lang::Lang::FormatNumber( m_CarryScore,true));

		if(m_pUIBonus1)
			m_pUIBonus1->SetTextA( lang::Lang::FormatNumber(m_BonusScore1 ,true));

		if(m_pUIBonus2)
			m_pUIBonus2->SetTextA( lang::Lang::FormatNumber(m_BonusScore2 ,true));

		
	}

	
	

}

void DELEGATE_CALL		FIGUILevelComplete::OnClickMedal(ui::UIWidget::WIDGET_EVENT Event, 
														 ui::UIWidget* pWidget)
{
	if(!pWidget)
		return;

	m_pPopup->Hide(NULL);
	

	int MedalType = 0;

	for(int i = 0; i < FIGGameCenter::ACHIEVEMENT_C; i++)
	{    		
		if(m_pUIMedals[i] == pWidget)
		{
			MedalType = i + 1;
			i =  (int)FIGGameCenter::ACHIEVEMENT_C;
		}

	}


	std::string TitleTxt = FIGGameCenter::Instance().GetString(MedalType);
	std::string InfoTxt = FIGGameCenter::Instance().GetMedalExplanation(MedalType);
	std::string TrophiImg = FIGGameCenter::Instance().GetMedalImageName(MedalType);

	//gameflow::UIPopup* pPopup = gameflow::UIPopupManager::Instance().StartPopup("ui/popup_medal_info.ui");
	FIGUIPopupAnimator* pPopupAnim  = FIGUIPopupAnimatorMgr::Instance().Show(FIGUIPopupAnimatorMgr::POPUP_NAMES_MEDALINFO);
	if(pPopupAnim && pPopupAnim->GetPopup())																													  
	{
		 gameflow::UIPopup* pPopup = pPopupAnim->GetPopup();

//#ifdef _PLATFORM_ANDROID     // deprecate 
		// i haven't implemented facebookconnect on adroid yet.
		if(pPopup->GetWidget("share_info"))
			pPopup->GetWidget("share_info")->SetIsVisible(false);

		if(pPopup->GetWidget("fb_share"))
			pPopup->GetWidget("fb_share")->SetIsVisible(false);
		
//#endif

		if(pPopup->GetWidget("share_info_txt"))
			pPopup->GetWidget("share_info_txt")->SetTextColor(0,0,0,1.0f);

		if(FIGVars::Instance()->GetInt( (int)FIGVars::VAR_NAMES_ACHIEVEMENT_1 + (int)FIGGameCenter::GOD_OF_ALIENS - 1)  == 1)
		{
			pPopup->GetWidget("share_info")->SetIsVisible(false);
		}

		pPopup->SetWidgetFunctor("button_ok",UI_DELEGATE(FIGUILevelComplete, OnClosePopupMedal));
		//pPopup->SetWidgetFunctor("fb_share",UI_DELEGATE(FIGUILevelComplete, OnButtonShare));

		if(pPopup->GetWidget("medal_img"))
			pPopup->GetWidget("medal_img")->SetOffImage(TrophiImg);

		if(pPopup->GetWidget("mdeal_info"))
			pPopup->GetWidget("mdeal_info")->SetTextA(InfoTxt);

		if(pPopup->GetWidget("title"))
			pPopup->GetWidget("title")->SetTextA(TitleTxt);

		if(pPopup->GetWidget("image_link"))
			pPopup->GetWidget("image_link")->SetTextA("http://www.2dstar.com/medal/" + TrophiImg + ".jpg");

		if(pPopup->GetWidget("info_stringbox"))
			pPopup->GetWidget("info_stringbox")->SetIsVisible(false);

		
	}
}

void DELEGATE_CALL		FIGUILevelComplete::OnClosePopupMedal(ui::UIWidget::WIDGET_EVENT Event, 
														 ui::UIWidget* pWidget)
{
	
	_LOG( MSG_COMMENT, "Medal Popup Close Button Clicked!");
	FIGUIPopupAnimatorMgr::Instance().GetPopup(FIGUIPopupAnimatorMgr::POPUP_NAMES_MEDALINFO)->GetPopup()->Hide(NULL);
	FIGUIPopupAnimatorMgr::Instance().Show(FIGUIPopupAnimatorMgr::POPUP_NAMES_GAMEOVER);
}

/*
void DELEGATE_CALL		FIGUILevelComplete::OnButtonShare(ui::UIWidget::WIDGET_EVENT Event, ui::UIWidget* pWidget)
{
#ifdef  _PLATFORM_IOS
	gameflow::UIPopup* pPopup = gameflow::UIPopupManager::Instance().StartPopup("ui/popup_medal_info.ui");
	if(pPopup)
	{
		const std::string Name = pPopup->GetWidget("share_text")->GetTextA();
		const std::wstring Caption = pPopup->GetWidget("title")->GetText();
		const std::wstring Desc = pPopup->GetWidget("mdeal_info")->GetText();
		const std::string Image = pPopup->GetWidget("image_link")->GetTextA();
		

		FBConnectCPlus::Instance().ShareToWall(
												Name,
												Caption,
												Desc,
												FIGConstants::ITUNE_LINK,
												Image,
												this
												);


		//test
		OnFBShareSucess();
	}
#endif
}


void			FIGUILevelComplete::OnFBShareSucess()
{
	
	//if(FIGVars::Instance()->GetInt( (int)FIGVars::VAR_NAMES_ACHIEVEMENT_1 + (int)FIGGameCenter::GOD_OF_ALIENS) == 0)
		FIGGameCenter::Instance()->UpdateValue(FIGGameCenter::GOD_OF_ALIENS,true,true);

	gameflow::UIPopup* pPopup = gameflow::UIPopupManager::Instance().GetPopup("ui/popup_medal_info.ui");
	if(pPopup)
	{
		pPopup->GetWidget("share_info")->SetIsVisible(false);		
		
	}
  
	m_ToCloseMedalInfoPopup = true;	
	LoadMedals();
	m_PopupReshowCounter = 2.5f;

}

void			FIGUILevelComplete::OnFBShareFail()
{

}
 */

void DELEGATE_CALL		FIGUILevelComplete::OnButtonFullVersion(ui::UIWidget::WIDGET_EVENT Event, ui::UIWidget* pWidget)
{
	//FIGUIRemoveAd::Instance().Show(NULL);
}

void DELEGATE_CALL		FIGUILevelComplete::OnButtonAndroids(ui::UIWidget::WIDGET_EVENT Event, ui::UIWidget* pWidget)
{
    
#ifdef _PLATFORM_IOS
    FIGIOSWrapper::Instance().FIG_GotoWebSite(FIGConstants::ITUNE_LINK);
#endif
    
#ifdef _PLATFORM_ANDROID
	Android_JNI_SendMessage(FUNC_gotoURL, 0);
#endif
}


void		FIGUILevelComplete::RefreshUI()
{
	ui::UIWidget* pWidget = m_pPopup->GetWidget("button_removead");
//#ifdef _PLATFORM_ANDROID

	if(pWidget)
	{
		pWidget->SetTextA("Rate Us");
	}
//#else


	
	if(FIGVars::Instance()->GetInt(FIGVars::VAR_NAMES_IS_FULL_VERSION) ||
       ((FIGVars*)FIGVars::Instance())->GetCurrentLevel() == 0
       )
	{
			
		if(pWidget)
		{
			pWidget->SetIsVisible(false);
		}

		ui::UIWidget* pButtonNext = m_pPopup->GetWidget("button_next");
		if(pButtonNext)
		{
			math::Vec2 Pos = pButtonNext->GetPosition();
			
			pButtonNext->SetPosition(math::Vec2(0.5f - (pButtonNext->GetSize().x * 0.5f) , Pos.y));
		}

	}         
	else
	{
		// LITE VERSION
		if(pWidget)
			pWidget->SetIsVisible(true);
        
        ui::UIWidget* pButtonNext = m_pPopup->GetWidget("button_next");
		if(pButtonNext)
		{
            pButtonNext->SetPosition(m_ButtonNextPosBackup);
        }
	}
//#endif
	

}


//void		FIGUILevelComplete::ForceHide()
//{
//	if(m_pPopup->GetPanel()->GetIsVisible() == false)
//		return;
//
//	OnClickScreen(ui::UIWidget::WE_LMB_CLICK,NULL);
//	gameflow::UIPopup::ForceHide();
//}

